package com.bigfreakindeals.Activities;


import java.util.ArrayList;

import com.bigfreakindeals.R;
import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Common.Tools;
import com.bigfreakindeals.Models.UniversityDeals;
import com.bigfreakindeals.Protocols.SoapHandlers.FAQHandler;
import com.bigfreakindeals.Protocols.SoapHandlers.LoginHandler;
import com.bigfreakindeals.Protocols.SoapHandlers.SettingsHandler;
import com.bigfreakindeals.Widgets.AlertManager;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.ToggleButton;




public class SettingsActivity extends BaseActivity implements OnClickListener{

    public static final String PREFS_NAME = "MyPrefsFile";
    
    ToggleButton rememberMe;
    ToggleButton newDeals;
    ToggleButton beanSays;

    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);	
		
		setContentView(R.layout.settings);
		
	
		
		
		
	
	}
	@Override
	public void onResume(){
		super.onResume();

		ApplicationEx.getInstance().currentTab = 2;
		
		getActivityView();
		
	}
	private static final String WEBSERVICE_SETTINGS_NOTIFICATIONS = "/webservices/services.php?action=deviceNotificationSettings&sessionToken=%sessionid&BeansSays=1&NewDeals=0";
	
	public void updateServer(boolean valuebeans,boolean valuedeals){
		//beansays = 0;
		//notification = 1
		if (ApplicationEx.getInstance().myProfile.getSessionID()!=null){
			final ArrayList<String> params = new ArrayList<String>();
				params.add(ApplicationEx.getInstance().myProfile.getSessionID());
				params.add(valuebeans?"1":"0");
				params.add(valuedeals?"1":"0");
		
			new Thread() {
				public void run() {
					try {
						sleep(5);
					} catch (Exception e) {
					}
					
					new SettingsHandler(Tools.getURL(Constant.GET_SETTINGSHANDLER,params));	
				}

			}.start();
			
		}
		
	}
	public void getActivityView(){
		
		final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		
		((TextView) findViewById(R.id.header_title)).setText("Settings");
		
		((TableLayout)findViewById(R.id.tableversion)).setBackgroundDrawable(Tools.getDrawableButtonGeneric(new int[]{0xffffffff, 0xffd0d0d0}, 10));
		((RelativeLayout)findViewById(R.id.containergray)).setBackgroundDrawable(Tools.getDrawableButtonGeneric(new int[]{0xffffffff, 0xffd0d0d0}, 10));
		
		
		if ((ApplicationEx.getInstance().myProfile.getSessionID() != null) && ((settings.getString("username", null)) != null)){

			((TextView)findViewById(R.id.signinout)).setText("Sign Out");
			((TextView)findViewById(R.id.signinout)).setTag(R.id.settings_sign_in_out_tag,"SIGN_OUT");
			
			rememberMe = (ToggleButton)findViewById(R.id.togglenewdeals);
			newDeals = (ToggleButton)findViewById(R.id.togglerememberme);
			beanSays = (ToggleButton)findViewById(R.id.togglebeansays);
			
			rememberMe.setVisibility(View.VISIBLE);
			newDeals.setVisibility(View.VISIBLE);
			beanSays.setVisibility(View.VISIBLE);
			
			newDeals.setChecked(true);
			newDeals.setClickable(true);
			newDeals.setEnabled(true);

			rememberMe.setChecked(true);
			rememberMe.setClickable(true);
			rememberMe.setEnabled(true);

			beanSays.setChecked(true);
			beanSays.setClickable(true);
			beanSays.setEnabled(true);
			
			final SharedPreferences.Editor editor = settings.edit();
		     
		      
			rememberMe.setOnClickListener(new OnClickListener() {
			    public void onClick(View v) {
			        // Perform action on clicks
			        if (rememberMe.isChecked()) {
			        	 editor.putBoolean("rememberme", true);
			        } else {
			        	editor.putBoolean("rememberme", false);
			        }
			        editor.commit();
			    }
			});

			newDeals.setOnClickListener(new OnClickListener() {
			    public void onClick(View v) {
			        // Perform action on clicks
			        if (newDeals.isChecked()) {
			            Log.i("check", "newdeals");
			            editor.putBoolean("newdeals", true);
			        } else {
			        	 editor.putBoolean("newdeals", false);
			        }
			        editor.commit();
			        
			        //updateserver
			        updateServer(beanSays.isChecked(),newDeals.isChecked());
			    }
			});
			
			beanSays.setOnClickListener(new OnClickListener() {
			    public void onClick(View v) {
			        // Perform action on clicks
			        if (beanSays.isChecked()) {
			           
			            editor.putBoolean("beansays", true);
			        } else {
			        	 editor.putBoolean("beansays", false);
			        }
			        editor.commit();
			        updateServer(beanSays.isChecked(),newDeals.isChecked());
			      }
			});

			newDeals.setChecked(ApplicationEx.getInstance().myProfile.isSettins_notificationNewDeals());
			beanSays.setChecked(ApplicationEx.getInstance().myProfile.isSettins_notificationbeanSays());
			rememberMe.setChecked(ApplicationEx.getInstance().myProfile.isSettings_rememberMe());
			
			((TextView)findViewById(R.id.textviewusername)).setVisibility(View.VISIBLE);
			
			((TextView) findViewById(R.id.textviewusername)).setText(settings.getString("username", null));

			
		}else {
			((TextView)findViewById(R.id.signinout)).setText("Sign In/Sign Up");
		
			((TextView)findViewById(R.id.signinout)).setTag(R.id.settings_sign_in_out_tag,"SIGN_IN");
			
			((TextView)findViewById(R.id.textviewusername)).setVisibility(View.GONE);
			((ToggleButton)findViewById(R.id.togglenewdeals)).setChecked(false);
			((ToggleButton)findViewById(R.id.togglenewdeals)).setClickable(false);
			((ToggleButton)findViewById(R.id.togglenewdeals)).setPressed(false);
			((ToggleButton)findViewById(R.id.togglenewdeals)).setEnabled(false);

			((ToggleButton)findViewById(R.id.togglerememberme)).setChecked(false);
			((ToggleButton)findViewById(R.id.togglerememberme)).setClickable(false);
			((ToggleButton)findViewById(R.id.togglerememberme)).setPressed(false);
			((ToggleButton)findViewById(R.id.togglerememberme)).setEnabled(false);

			((ToggleButton)findViewById(R.id.togglebeansays)).setChecked(false);
			((ToggleButton)findViewById(R.id.togglebeansays)).setClickable(false);
			((ToggleButton)findViewById(R.id.togglebeansays)).setPressed(false);
			((ToggleButton)findViewById(R.id.togglebeansays)).setEnabled(false);

		}


		
		
		((TextView)findViewById(R.id.signinout)).setOnClickListener(this); 
		
		updateUniversityTheme();
			
	}
	
	//university specific settings in this case just BG
	public void updateUniversityTheme(){
		
	 	((RelativeLayout)findViewById(R.id.settingmain)).setBackgroundColor(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().color_school_bg + (-16777216));
		
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
		
		if (  keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	        
	    	((TabActivity)getParent()).getTabHost().setCurrentTab(0);
	    	return true;
	    	
		}
    	return super.onKeyDown(keyCode,event);
    	   
	}

	
	public void SignIn(){
		Intent intent = new Intent(this, LoginActivity.class);
		intent.putExtra(Constant.TAG_LOGINFROM, Constant.TAG_LOGINFROM_SETTINGS);
		startActivity(intent);
 	}

	public void SignOut(){
		ApplicationEx.getInstance().myProfile.setLogin(false);
		ApplicationEx.getInstance().myProfile.setSessionID(null);
		
		AlertManager.alertOK(this, "You are now signed out.","OK");
		
		getActivityView();
		
		
	}
	
	private void updateSetting(String sessionid, boolean beansSays,boolean deals) {
		// TODO Auto-generated method stub
			
		final ArrayList<String> params = new ArrayList<String>();
		params.add(sessionid);
		params.add(beansSays?"1":"0");
		params.add(deals?"1":"0");
			
		final Context context =this;
		new Thread() {
			@Override
			public void run() {
				try {
					sleep(5);
				} catch (Exception e) {
				}
				new LoginHandler(Tools.getURL(Constant.GET_LOGIN, params ),context);
				
			}

		}.start();
		
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		switch (id) {
		
		case R.id.signinout:
			String tag = v.getTag(R.id.settings_sign_in_out_tag).toString();
			
			if (tag.compareTo("SIGN_IN")  == 0)
				SignIn();
			else 
				SignOut();
			break;
		case R.id.footer_activedeals:
			callActivedeals(this, Settings.class);
		default:
			break;
		}
		
	}



}
